package com.zhangtai.modules.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.ProtocolDao;
import com.zhangtai.modules.dao.ProtocolPersonnelDao;
import com.zhangtai.modules.dto.ProtocolDto;
import com.zhangtai.modules.entity.contract.ProtocolEntity;
import com.zhangtai.modules.entity.contract.ProtocolPersonnelEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.service.contract.ProtocolPersonnelService;
import com.zhangtai.modules.service.contract.ProtocolService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.vo.ProtocolVo;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import com.zhangtai.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;


/**
 * 培训协议
 */
@RestController
@Api(tags = "培训协议接口")
@RequestMapping("protocol")
@Slf4j
public class ProtocolController {
    @Autowired
    private ProtocolService protocolService;
    @Autowired
    private ProtocolDao protocolDao;
    @Autowired
    private LoginController loginController;
    @Autowired
    private ProtocolPersonnelDao protocolPersonnelDao;
    @Autowired
    private ProtocolPersonnelService protocolPersonnelService;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private JobController jobController;
    @Autowired
    private EsignController esignController;

    @GetMapping("/getProtocolPage")
    @ApiOperation(value = "分页查询培训协议列表")
    public R getProtocolPage(@RequestParam(value = "projectName", required = false) String projectName,
                             @RequestParam(value = "trainingStartTime", required = false) String trainingStartTime,
                             @RequestParam(value = "trainingEndTime", required = false) String trainingEndTime,
                             @RequestParam(value = "trainingType", required = false) Integer trainingType,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                             HttpServletRequest request) throws Exception {

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        PageResult pageResult = protocolService.queryPage(orgIds, projectName, trainingStartTime, trainingEndTime, trainingType, pageNum, pageSize);

        return R.ok(pageResult);
    }


    @PostMapping("/saveAndUpdateProtocol")
    @ApiOperation(value = "保存或修改培训协议")
    @SysAuthorityLog(value = "保存或修改培训协议")
    @Transactional
    public R saveAndUpdateProtocol(@RequestBody @Valid ProtocolVo protocolVo, HttpServletRequest request) throws Exception {

        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return R.error("请先登录");
        }
        ProtocolEntity protocolEntity = BeanUtilsMabach.doToDto(protocolVo, ProtocolEntity.class);
        if (protocolVo.getId() == null) {
            protocolEntity.setCreateCode(data.getString("usercode"));
            protocolEntity.setCreateName(data.getString("name"));
            protocolEntity.setCreateTime(new Date());
            protocolEntity.setUnitId(data.getLong("depId"));
            protocolEntity.setTrainingNum(protocolVo.getProtocolPersonnelEntityArrayList().size());
            protocolService.saveE(protocolEntity);
        } else {
            protocolPersonnelDao.delete(new QueryWrapper<ProtocolPersonnelEntity>().eq("protocol_id", protocolEntity.getId()));
            protocolService.updateByIdE(protocolEntity);
        }
        if (!CollectionUtils.isEmpty(protocolVo.getProtocolPersonnelEntityArrayList())) {
            for (ProtocolPersonnelEntity protocolPersonnelEntity : protocolVo.getProtocolPersonnelEntityArrayList()) {
                EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(protocolPersonnelEntity.getOid());
                protocolPersonnelEntity.setOrgId(employeeInfoEntity.getOrgId());
                protocolPersonnelEntity.setJobId(employeeInfoEntity.getJobId());
                protocolPersonnelEntity.setCreateTime(new Date());
                protocolPersonnelEntity.setProtocolId(protocolEntity.getId());
                protocolPersonnelEntity.setUnitId(employeeInfoEntity.getUnitId());
                protocolPersonnelService.saveE(protocolPersonnelEntity);
            }
        }
        return R.ok();
    }

    @GetMapping("/getProtocolPersonnel")
    @ApiOperation(value = "根据培训id获取员工培训信息")
    public R getProtocolPersonnel(@RequestParam(value = "protocolId") String protocolId) {
        List<ProtocolDto> protocolDtoList = protocolPersonnelDao.getProtocolPersonnelListByProtocolId(Long.valueOf(protocolId));
        for (ProtocolDto protocolDto : protocolDtoList) {
            if (protocolDto.getJobId() != null && StringUtils.isEmpty(protocolDto.getJobname()))
                protocolDto.setJobname(jobController.getJobName(protocolDto.getJobId()));
            if (protocolDto.getOrgId() != null && StringUtils.isEmpty(protocolDto.getOrgname()))
                protocolDto.setOrgname(jobController.getOrgNameById(protocolDto.getOrgId()));
            if (protocolDto.getUnitId() != null && StringUtils.isEmpty(protocolDto.getUnitname()))
                protocolDto.setUnitname(jobController.getOrgNameById(protocolDto.getUnitId()));
        }
        return R.ok(protocolDtoList);
    }

    @DeleteMapping("/deleteProtocolById")
    @ApiOperation(value = "删除培训信息")
    @Transactional
    public R deleteProtocolByI(@RequestParam(value = "id") String id) {
        protocolDao.deleteById(id);
        protocolPersonnelDao.delete(new QueryWrapper<ProtocolPersonnelEntity>().eq("protocol_id", id));
        return R.ok();
    }


    @GetMapping("/updateProtocolStatusById")
    @ApiOperation(value = "修改培训信息状态  发送")
    @Transactional
    public R updateProtocolStatusById(@RequestParam(value = "id") String id, HttpServletRequest request) throws Exception {

        ProtocolEntity protocolEntity = protocolService.getByIdE(Long.valueOf(id));
        List<ProtocolPersonnelEntity> protocolPersonnelEntityList = protocolPersonnelDao.selectList(new QueryWrapper<ProtocolPersonnelEntity>()
                .eq("protocol_id", id));
        for (ProtocolPersonnelEntity protocolPersonnelEntity : protocolPersonnelEntityList) {
            esignController.saveProtocolInfo(protocolPersonnelEntity.getId().toString(), request);
            ;
        }
        protocolEntity.setStatus(1);
        protocolService.updateByIdE(protocolEntity);
        return R.ok();
    }

    @GetMapping("/getProtocolPersonnelPage")
    @ApiOperation(value = "分页查询培训员工协议信息列表")
    public R getProtocolPersonnelPage(@RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "code", required = false) String code,
                                      @RequestParam(value = "projectName", required = false) String projectName,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                      HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        Page<ProtocolDto> page = new Page<ProtocolDto>(pageNum, pageSize);
        List<ProtocolDto> protocolDtoList = protocolPersonnelDao.getProtocolPersonnelList(orgIds, name, code, projectName, page);
        for (ProtocolDto protocolDto : protocolDtoList) {
            if (protocolDto.getJobId() != null && StringUtils.isEmpty(protocolDto.getJobname()))
                protocolDto.setJobname(jobController.getJobName(protocolDto.getJobId()));
            if (protocolDto.getOrgId() != null && StringUtils.isEmpty(protocolDto.getOrgname()))
                protocolDto.setOrgname(jobController.getOrgNameById(protocolDto.getOrgId()));
            if (protocolDto.getUnitId() != null && StringUtils.isEmpty(protocolDto.getUnitname()))
                protocolDto.setUnitname(jobController.getOrgNameById(protocolDto.getUnitId()));
        }
        page.setRecords(protocolDtoList);
        return R.ok(new PageResult<ProtocolDto>(page));
    }

    @GetMapping("/updateProtocolPersonnelStatus")
    @ApiOperation(value = "修改培训人员信息状态 为终止")
    @Transactional
    public R updateProtocolPersonnelStatus(@RequestParam(value = "id") String id, @RequestParam(value = "remarks", required = false) String remarks) {
        ProtocolPersonnelEntity protocolPersonnelEntity = protocolPersonnelService.getByIdE(Long.valueOf(id));
        protocolPersonnelEntity.setStatus(4);
        protocolPersonnelEntity.setRemarks(remarks);
        protocolPersonnelEntity.setConsummationTime(new Date());
        protocolPersonnelService.updateByIdE(protocolPersonnelEntity);
        return R.ok();
    }

    @GetMapping("/updateProtocolPersonnelStatusFive")
    @ApiOperation(value = "修改培训人员信息状态 为线下签署")
    @Transactional
    public R updateProtocolPersonnelStatusFive(@RequestParam(value = "id") String id, @RequestParam(value = "contractOssUrl", required = false) String contractOssUrl) {
        ProtocolPersonnelEntity protocolPersonnelEntity = protocolPersonnelService.getByIdE(Long.valueOf(id));
        protocolPersonnelEntity.setStatus(2);
        protocolPersonnelEntity.setContractOssUrl(contractOssUrl);
        protocolPersonnelService.updateByIdE(protocolPersonnelEntity);
        List<ProtocolPersonnelEntity> protocolPersonnelEntityList = protocolPersonnelDao.selectList(new QueryWrapper<ProtocolPersonnelEntity>()
                .eq("protocol_id", protocolPersonnelEntity.getProtocolId()).and(i->i.eq("status", 0).or().eq("status", 1)));
        if (CollectionUtils.isEmpty(protocolPersonnelEntityList)) {
            ProtocolEntity protocolEntity = protocolService.getByIdE(protocolPersonnelEntity.getProtocolId());
            protocolEntity.setStatus(2);
            protocolService.updateByIdE(protocolEntity);
        }
        return R.ok();
    }
}
